package com.leikooo.yupicturebackend.manager;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.leikooo.yupicturebackend.config.CosClientConfig;
import com.leikooo.yupicturebackend.exception.BusinessException;
import com.leikooo.yupicturebackend.exception.ErrorCode;
import com.leikooo.yupicturebackend.exception.ThrowUtils;

import com.leikooo.yupicturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author <a href="https://github.com/lieeew">leikooo</a>
 */
@Service
@Slf4j
public class FileManager {
    /**
     * 1 兆
     */
    private static final long ONE_M = 1024 * 1024L;

    private static final List<String> ALLOW_FORMAT_LIST = Arrays.asList("jpeg", "jpg", "png", "webp");

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 上传图片
     * @param multipartFile 文件
     * @param uploadPathPrefix 上传路径的前缀
     * @return
     */

   public UploadPictureResult uploadPicture(MultipartFile multipartFile,String uploadPathPrefix) {
       // 校验文件
       this.validPicture(multipartFile);
       String uuid = RandomUtil.randomString(16);
       String originalFilename = multipartFile.getOriginalFilename();
       // 拼接文件上传路径 不使用原始文件路径
       String uploadFileName = String.format("%s_%s.%s", DateUtil.formatDate(new Date()), uuid, FileUtil.getSuffix(originalFilename));
       String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFileName);
       File file = null;
       try {
           // 上传文件
           file = File.createTempFile(uploadPath, null);
           multipartFile.transferTo(file);
           PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
           // 获取文件基本信息
           ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
           // 宽高
           int picWidth = imageInfo.getWidth();
           int picHeight = imageInfo.getHeight();
           double picScan = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
           // 封装返回结果
           UploadPictureResult uploadPictureResult = new UploadPictureResult();
           uploadPictureResult.setUrl(cosClientConfig.getHost()+uploadPath);
           uploadPictureResult.setPicName(FileUtil.mainName(originalFilename));
           uploadPictureResult.setPicSize(FileUtil.size(file));
           uploadPictureResult.setPicWidth(picWidth);
           uploadPictureResult.setPicHeight(picHeight);
           uploadPictureResult.setPicScale(picScan);
           uploadPictureResult.setPicFormat(imageInfo.getFormat());
           return uploadPictureResult;
       }catch (Exception e){
           log.error("上传文件异常",e);
           throw new BusinessException(ErrorCode.SYSTEM_ERROR,"上传失败");

       } finally {
           // 临时文件清理
           this.deleteTempFile(file);
       }

   }

    /**
     * 删除临时文件
     */
    public void deleteTempFile(File file) {
        if (file == null) {
            return;
        }
        // 删除临时文件
        boolean deleteResult = file.delete();
        if (!deleteResult) {
            log.error("file delete error, filepath = {}", file.getAbsolutePath());
        }
    }
    /**
     * 校验文件
     * @param multipartFile
     */
   public void validPicture(MultipartFile multipartFile) {
       ThrowUtils.throwIf(multipartFile == null , ErrorCode.PARAMS_ERROR,"文件不能为空");
       // 校验文件大小
       long fileSize = multipartFile.getSize();

       ThrowUtils.throwIf(fileSize > 2 * ONE_M,ErrorCode.PARAMS_ERROR,"文件大小不能超过2M");
       // 校验文件后缀
       String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
       // 允许上传的文件后缀
       ThrowUtils.throwIf(!ALLOW_FORMAT_LIST.contains(fileSuffix),ErrorCode.PARAMS_ERROR,"文件类型错误");
   }
}

